<?php
class Bizprofile_MessageController extends Zend_Controller_Action {

    public function inboxAction() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }else{
			$user = $auth->getIdentity();
			$redirectFlag = false;            			
            if($user->enterprise != null){
				$enterprise_id_edit = $this->getRequest()->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit)
					$redirectFlag = true;
			}else $redirectFlag = true;		
			if($redirectFlag){
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				$redirector->gotoUrl('');								
			}					
		}		        
        if($user->enterprise){
            $enterprise_id = $user->enterprise->id;

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $messageDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDetailDao();
            $messageDao->setDbConnection($conn);

            $request    = $this->getRequest();
            $pageIndex     = $request->getParam('pageIndex', 1);
            $perPage = 10;
            $offset     = ($pageIndex - 1) * $perPage;
            $exp = array(
            'enterprise_id' => $enterprise_id,
            'parentmessageid' => 1
            );

            $message = $messageDao->find($offset, $perPage, $exp);
            $total   = $messageDao->count($exp);
			
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($message, $total));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('message', $message);
            $this->view->assign('numMessage', $total);

            $this->view->assign('paginator', $paginator);

            $arrParamMessage = array(
                'enterprise_id' => $user->enterprise->id,
                'enterprise_name' => Tomato_Utility_String::removeSign($user->enterprise->company_name_en, '-', true)
            );
            $this->view->assign('paginatorOptions', array(
                'path'        => $this->view->url($arrParamMessage, 'bizprofile_message_inbox'),
                    'itemLink' => 'page-%d'
            ));

            /**
            * Enterprise info
            **/
            $this->view->assign('enterprise', $user->enterprise);
            
            /**
             * Enterprise models access to data
            **/
            $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
            $enterpriseDao->setDbConnection($conn);

            /**
            * Get enterprise follow message
            **/
            $arrEnt = array();
            $arrUser = array();
            foreach($message as $m_row){
            	if($m_row->fromenterprise_id != 0) // Người gửi là Enterprise
            	{
	                $objEnterprise = $enterpriseDao->getById($m_row->fromenterprise_id);
	                $arrEnInfo = array(
	                    'e_id' => $objEnterprise->id,
	                    'e_name' => $objEnterprise->company_name_en
	                	);
	                $arrEnt[$m_row->id] = $arrEnInfo;
            	}
            	else // Mgười gửi là User bình thường
            	{
            		//echo $m_row->fromuser_id;	
					/** Enterprise User model access to db */
			        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
			        $userDao->setDbConnection($conn);   

			        /* Get user info */
			        $user = $userDao->getByUserName($m_row->fromuser_name);          		
            		$arrUser[] = $user;
            	}
            }
            if(isset($arrEnt))
            {
            	$this->view->assign('arrEnt', $arrEnt);
            }
            else
            {
            	$this->view->assign('arrUser', $arrUser);
            }
        }
    }

    public function sendAction() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }else{
			$user = $auth->getIdentity();
			$redirectFlag = false;            			
            if($user->enterprise != null){
				$enterprise_id_edit = $this->getRequest()->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit)
					$redirectFlag = true;
			}else $redirectFlag = true;		
			if($redirectFlag){
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				$redirector->gotoUrl('');								
			}					
		}
        if($user->enterprise){
            $enterprise_id = $user->enterprise->id;

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $messageDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDetailDao();
            $messageDao->setDbConnection($conn);

            $request    = $this->getRequest();
            $pageIndex     = $request->getParam('pageIndex', 1);
            $perPage = 10;
            $offset     = ($pageIndex - 1) * $perPage;
            $exp = array(
            'enterprise_id' => $enterprise_id,
            'parentmessageid' => 0
            );

            $message = $messageDao->find($offset, $perPage, $exp);
            $total   = $messageDao->count($exp);
            
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($message, $total));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('message', $message);
            $this->view->assign('numMessage', $total);

            $this->view->assign('paginator', $paginator);

            $arrParamMessage = array(
                'enterprise_id' => $user->enterprise->id,
                'enterprise_name' => Tomato_Utility_String::removeSign($user->enterprise->company_name_en, '-', true)
            );
            $this->view->assign('paginatorOptions', array(
                'path'        => $this->view->url($arrParamMessage, 'bizprofile_message_send'),
                    'itemLink' => 'page-%d'
            ));

            /**
            * Enterprise info
            **/
            $this->view->assign('enterprise', $user->enterprise);

            /**
             * Enterprise models access to data
            **/
            $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
            $enterpriseDao->setDbConnection($conn);

            /**
            * Get enterprise follow message
            **/
            $arrEnt = array();
            foreach($message as $m_row){
                $objEnterprise = $enterpriseDao->getById($m_row->fromenterprise_id);
                $arrEnInfo = array(
                    'e_id' => $objEnterprise->id,
                    'e_name' => $objEnterprise->company_name_en
                );
                $arrEnt[$m_row->id] = $arrEnInfo;
            }
            $this->view->assign('arrEnt', $arrEnt);
        }
    }

    public function addAction() {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {		
            $user = $auth->getIdentity();
			/*
			$redirectFlag = false;            			
            if($user->enterprise != null){
				$enterprise_id_edit = $this->getRequest()->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit)
					$redirectFlag = true;
			}else $redirectFlag = true;		
			if($redirectFlag){
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				$redirector->gotoUrl('');								
			}
			*/		
            $request = $this->getRequest();
			//print_r($request->getParams());
            $enterprise_id = $request->getParam('reply_id');

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $enterpriseDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
            $enterpriseDao->setDbConnection($conn);
            $enterprise = $enterpriseDao->getById($enterprise_id);

            if($request->isPost()){
                $message = new Bizprofile_Models_Message(array(
                    'fromuser_id'             => $user->user_id,
                    'fromuser_name'           => $user->user_name,
                    'fromenterprise_id'        => ($user->enterprise) ? $user->enterprise->id : 0,
                    'fromenterprise_name'    => ($user->enterprise) ? $user->enterprise->company_name_vn : '',
                    'title'                    => $request->getPost('title'),
                    'message'                => $request->getPost('content'),
                    'touserarray'            => null,
                    'toenterprisearray'        => serialize(array('enterprise_id' => $enterprise->id, 'company_name_vn' => $enterprise->company_name_vn)),
                    'dateline_send'            => time(),
                    'dateline_read'            => 0
                ));

                $messageDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDao();
                $messageDao->setDbConnection($conn);
                $messageid = $messageDao->add($message);

                $sendMessage = new Bizprofile_Models_MessageDetail(array(
                    'messageid'             => $messageid,
                    'user_id'               => $user->user_id,
                    'enterprise_id'            => ($user->enterprise) ? $user->enterprise->id : 0,
                    'messageread'            => 1,
                    'parentmessageid'        => 0
                ));
                $sendMessageDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDetailDao();
                $sendMessageDao->setDbConnection($conn);
                $sendid = $sendMessageDao->add($sendMessage);

                $receiveMessage = new Bizprofile_Models_MessageDetail(array(
                    'messageid'             => $messageid,
                    'user_id'               => 0,
                    'enterprise_id'            => $enterprise->id,
                    'messageread'            => 0,
                    'parentmessageid'        => $sendid
                ));
                $receiveid = $sendMessageDao->add($receiveMessage);

                if ($receiveid > 0) {
                    $arrParamMessage = array(
                        'enterprise_id' => $user->enterprise->id,
                        'enterprise_name' => Tomato_Utility_String::removeSign($user->enterprise->company_name_en, '-', true)
                    );
                    $this->_redirect($this->view->serverUrl() . $this->view->url($arrParamMessage, 'bizprofile_message_inbox'));
                }
            }
            $this->view->assign('enterprise', $enterprise);
            /** Khanh *****************************************************************************************************
		    * Kiem tra la user chua login, hay user da login, la DN khach, hay DN doi tac
		    * $user_entity = 1 : User chua login
		    * $user_entity = 2 : User da login, nhung ko la DN
		    * $user_entity = 3 : User da login, la DN khach
		    * $user_entity = 4 : User da login, la DN doi tac
		    **/
	        
	        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
			$permissionDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getPermissionDao();
			$permissionDao->setDbConnection($conn);
	        //$auth = Zend_Auth::getInstance();
			if ($auth->hasIdentity()) 
			{ 
			    $user = $auth->getIdentity();
			    if(!isset($user->enterprise->id))
			    {
			      	$user_entity = 2; // user da login, nhung ko phai la DN
			    }
				else
				{
				   	$partnerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getPartnerDao();
			        $partnerDao->setDbConnection($conn);
			
			        $pageIndex     = 1;
			        $perPage = 5;
			        $offset     = ($pageIndex - 1) * $perPage;
			        $exp = array(
			            'relationid' => $params['enterprise_id'],
			            'partner_type' => 'buddy',
			            'partner_status' => 'yes',
						'deleted'		 => 0
			        );
							
			        //* In ralationship
			        $partners = $partnerDao->find($offset, $perPage, $exp);
			        $numPartners   = $partnerDao->count($exp);
			             
			        $user_entity = 3;// DN khach
			        $request = $this->getRequest();
			        foreach($partners as $row):
						$expRecomment = array(
						'relationid' => $row->relationid,
						'enterprise_id' => $row->enterprise_id, // DN doi tac
						);
						if($user->enterprise->id == $row->enterprise_id)
						{
							$user_entity = 4; // DN doi tac
						}
					endforeach;
				}
			}
			else 
			{
			   	$user_entity = 1; // user chua login 
			}
				
			$this->view->assign('user_entity', $user_entity);
				
			$permission = $permissionDao->getPermissionByUserEntity($enterprise_id, $user_entity);
			if($permission != null){
				$permission->enterprise_info = unserialize($permission->enterprise_info);			
				$this->view->assign('permission', $permission);
			}
	    	if ($auth->hasIdentity()) { 
		            $user = $auth->getIdentity();
					if($user->enterprise){
						if($user->enterprise->id == $enterprise_id) // user đã login thuộc DN đang xem
				    	{
				    		$permission_viewall = 1;
				    		$this->view->assign('permission_viewall', $permission_viewall);
				    	}
					}
	        	}
			/**
			* END : Kiem tra la user chua login, hay user da login, la DN khach, hay DN doi tac
			*****************************************************************************************************/
        }
        else {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }
    }

    public function deleteAction() {

        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }else{
			$user = $auth->getIdentity();
			$redirectFlag = false;            			
            if($user->enterprise != null){
				$enterprise_id_edit = $this->getRequest()->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit)
					$redirectFlag = true;
			}else $redirectFlag = true;		
			if($redirectFlag){
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				$redirector->gotoUrl('');								
			}					
		}
        if($user->enterprise){
            $message_id = $request->getParam('message_id');

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $messageDetailDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDetailDao();
            $messageDetailDao->setDbConnection($conn);

            $messageDetail = $messageDetailDao->getById($message_id);
            if($messageDetail != null && $messageDetail->enterprise_id == $user->enterprise->id){
                $messageDetailDao->delete($message_id);
            }

            $arrParamMessage = array(
                'enterprise_id' => $user->enterprise->id,
                'enterprise_name' => Tomato_Utility_String::removeSign($user->enterprise->company_name_en, '-', true)
            );
            $this->_redirect($this->view->serverUrl() . $this->view->url($arrParamMessage, 'bizprofile_message_inbox'));
        }
        $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
    }

    public function viewAction(){
        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }else{
			$user = $auth->getIdentity();
			$redirectFlag = false;            			
            if($user->enterprise != null){
				$enterprise_id_edit = $this->getRequest()->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit)
					$redirectFlag = true;
			}else $redirectFlag = true;		
			if($redirectFlag){
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				$redirector->gotoUrl('');								
			}					
		}
        if($user->enterprise){
            $message_id = $request->getParam('message_id');
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $messageDetailDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDetailDao();
            $messageDetailDao->setDbConnection($conn);

            $messageDetail = $messageDetailDao->getById($message_id);
            if($messageDetail != null && $messageDetail->enterprise_id == $user->enterprise->id){
                if($messageDetail->messageread == 0){
                    $messageDetail->messageread = 1;
                    $messageDetailDao->update($messageDetail);

                    $messageDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getMessageDao();
                    $messageDao->setDbConnection($conn);
                    $message = $messageDao->getById($messageDetail->messageid);

                    $message->dateline_read = time();
                    $messageDao->update($message);
                }
                $this->view->assign('message', $messageDetail);
            }

            /**
            * Enterprise info
            **/
            $this->view->assign('enterprise', $user->enterprise);

            if($messageDetail->fromenterprise_id != 0) // Người gửi là Enterprise
            {
	            /**
	             * Enterprise models access to data
	            **/
	            $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
	            $enterpriseDao->setDbConnection($conn);
	
	            /**
	            * Get enterprise follow message
	            **/
	
	            $objEnterprise = $enterpriseDao->getById($messageDetail->fromenterprise_id);
	            $arrEnInfo = array(
	                'e_id' => $objEnterprise->id,
	                'e_name' => $objEnterprise->company_name_en
	            );
	            $this->view->assign('arrEnInfo', $arrEnInfo);
            }
            else // Nguoi gui la User 
            {
        		/** Enterprise User model access to db */
		        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
		        $userDao->setDbConnection($conn);   

		        /* Get user info */
		        $user = $userDao->getByUserName($messageDetail->fromuser_name);  
		        $this->view->assign('UserInfo', $user);
            }          
        }
    }
}